package com.xianggu.protocol.server;

import com.xianggu.protocol.EnumConstants;
import com.xianggu.spring.XiangGuApplicationContent;
import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

/**
 * @author chengjy
 * @date 2025/3/8
 */
public class RpcServer {

    public static void start(Class configClass ,  String localhost, int port) {
        // 启动Spring容器，加载bean
        XiangGuApplicationContent applicationContent = new XiangGuApplicationContent(configClass);

        //读取用户的配置
        // 1. 创建嵌入式Tomcat实例
        Tomcat tomcat = new Tomcat();

        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

        Connector connector = new Connector();
        connector.setPort(port);

        // 3. 配置Tomcat的Servlet容器
        Engine engine = new StandardEngine();
        engine.setDefaultHost(localhost);

        StandardHost host = new StandardHost();
        host.setName(localhost);

        String contextPath = "";
        Context context = new StandardContext();
        context.setPath( contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        // 2. 配置Spring应用上下文
        tomcat.addServlet( contextPath , "rpc" , new XiangguRPCServlet(applicationContent));
        context.addServletMappingDecoded(  EnumConstants.NETWORK_PATH, "rpc" );
        tomcat.addServlet( contextPath , "dispatcher" , new XiangguDispatcherServlet(applicationContent));
        context.addServletMappingDecoded( "/*" , "dispatcher" );

        // 4. 启动Tomcat并阻塞
        try {
            tomcat.start();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
        System.out.println("启动Tomcat容器 端口：" + port);

        server.await();
    }
}
